package com.wsl.HealthChallenge.models;

import java.io.Serializable;

import javax.jdo.JDOHelper;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;

/**
 * 
 * @author mark
 */
@PersistenceCapable
public class UserStats implements Serializable, Comparable<UserStats> {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Persistent
    private String name;

    @Persistent
    private String googleHealthSessionToken;

    @Persistent
    private float score;

    /** The last time when the score was updated. */
    @Persistent
    private long lastUpdateTimestamp;

    /**
     * 
     * @param name
     * @param score
     * @param googleHealthSessionToken
     */
    public UserStats(String name, float score, String googleHealthSessionToken) {
        this.name = name;
        this.score = score;
        lastUpdateTimestamp = 0;
        this.googleHealthSessionToken = googleHealthSessionToken;
    }

    /**
     * @return the user's name.
     */
    public String getName() {
        return name;
    }

    /**
     * @return the score the user achieved in the challenge.
     */
    public float getScore() {
        return score;
    }

    /**
     * Sets the score value for this user in this challenge.
     * @param score
     */
    public void setScore(float score) {
        this.score = score;
        this.lastUpdateTimestamp = System.currentTimeMillis();
        JDOHelper.makeDirty(this, "score");
        JDOHelper.makeDirty(this, "lastUpdateTimestamp");
    }

    public long getLastUpdateTimestamp() {
        return lastUpdateTimestamp;
    }

    /**
     * @return the user's Google health session token.
     */
    public String getGoogleHealthSessionToken() {
        return googleHealthSessionToken;
    }

    /**
     * Sets the Google Health token to the given value.
     * @param googleHealthSessionToken
     */
    public void setGoogleHealthSessionToken(String googleHealthSessionToken) {
        this.googleHealthSessionToken = googleHealthSessionToken;
    }

    /**
     * Compares the UserStats by score. This is needed for showing a sorted list of 
     * participants on the competition page (top 10 and 10 people around you).
     */
    @Override
    public int compareTo(UserStats otherUserStats) {
        if (!(otherUserStats instanceof UserStats)) {
            throw new ClassCastException("A UserStats object expected.");
        }
        float otherUserScore = ((UserStats) otherUserStats).getScore();  
        if (this.score > otherUserScore) {
            return 1;
        } else if (this.score < otherUserScore) {
            return -1;
        } else {
            return 0;
        }
    }

    public void setName(String displayedName) {
        name = displayedName;
    }
}